package cn.git;

import javassist.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * @description: 类文件转换器
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-12-19
 */
public class ClassFileTransformerDemo implements ClassFileTransformer {
    /**
     * 当字节码第一次被加载时，会调用该方法
     * @param className 加载的类的全限定名，包含包名，例如：cn/git/service/TestService/test
     *
     * @return 需要增强就返回增强后的字节码，否则返回null
     */
    @Override
    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {
        // 拦截指定类的字节码
        byte[] bytes = null;
        if ("cn/git/service/TestService".equals(className)) {
            // 创建新的 ClassPool 实例
            ClassPool classPool = new ClassPool();

            // 添加系统类路径
            classPool.appendSystemPath();

            // 添加自定义类路径
            classPool.insertClassPath(new LoaderClassPath(loader));
            CtClass ctClass;
            try {
                ctClass = classPool.get("cn.git.service.TestService");
                CtMethod method = ctClass.getDeclaredMethod("test", new CtClass[]{classPool.get("java.lang.String")});
                method.insertBefore("{System.out.println(\"hello world\");}");
                bytes = ctClass.toBytecode();
                System.out.println("增强代码成功 class : " + className);
            } catch (NotFoundException e) {
                System.out.println("未找到类: " + "cn.git.service.TestService");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("获取类失败");
            }
        }

        return bytes;
    }
}
